package com.mlx.permission.function;

import com.mlx.permission.entity.Permission;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 抽象的功能验证器：
 *
 * @param <P>
 */
public abstract class AbstractFunctionValidator<P extends Permission> implements IFunctionValidator<P> {


    @Override
    public boolean isHavePermission(String permissionValue) {
        // 如果是开放实体，返回true
        if (isOpenEntity()){
            return true;
        }

        // 获取权限容器
        Set<String> container = getContainer();

        // 判断容器中是否有指定权限
        return container.contains(permissionValue);
    }

    @Override
    public Set<String> getContainer() {
        Set<String> container = new HashSet<>();

        // 获取当前实体所有权限
        Collection<P> permissionCollection = getPermissionCollection();

        // 将权限放入容器
        if (permissionCollection != null && !permissionCollection.isEmpty()){
            container.addAll(permissionCollection.stream().map(P::getPermissionValue).collect(Collectors.toSet()));
        }

        return container;
    }

}
